#include "log.hpp"
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>

static void UserManual()
{
    std::cout << "please:./UDPClient ip port" << std::endl;
}

int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        UserManual();
        exit(-1);
    }
    // 首先创建套接字
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    // 注意，此套接字不可显示绑定 - 不能绑定确定的port

    // 将服务器端套接字结构初始化好
    struct sockaddr_in server;
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[2]));
    server.sin_addr.s_addr = inet_addr(argv[1]);  // 首先点分式转化为数字然后转化为网络字节序保存起来

    char buffer[1024];
    while (true)
    {
        std::cout << "请输入# ";
        std::string message;
        std::getline(std::cin, message);
        sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr*)&server, sizeof server);

        // 接收消息
        struct sockaddr_in _server;
        socklen_t server_len = sizeof(_server);
        bzero(&_server, server_len);
        ssize_t s = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&_server, &server_len);
        if (s > 0)
        {
            buffer[s] = '\0';
            std::cout << "server echo# " << buffer << std::endl;
        }
    }
    return 0;
}